/**
 * Created by tuyidong on 2017/5/3.
 */
import React, {Component, PropTypes} from 'react'
import {Row, Col, Form, Input, Select, Button, Table, Pagination, Modal, Upload, Icon, Tag, notification } from 'antd'
import {Link} from 'react-router'

const FormItem = Form.Item;
const Option = Select.Option;
const CheckableTag = Tag.CheckableTag;
const openNotificationWithIcon = (type,message,description) => {
    notification[type]({
        message: message,
        description: description
    });
};

const addGoodsBox = {
    showGoodNameSelect:false,
    showRecordInput: false,
    showGoodsID: false,
    showGoodsSkuid: false,
    ableEditType:false,
    goodsSourceName: null,//商品来源名称
    goodsSource: null,//商品来源标识
    goodsName: null,//商品名称
    goodsId: null,//商品编码
    goodsTypeName: null,//商品类型名称
    goodsType: null,//商品类型标识编码
    integralPrice: null,//赠送积分数量
    goodsDesc: null,//商品介绍
    goodsSkuid: null,
    skuList:[],//skulist数组
    skuList2:[],//skulist的拷贝，方便tag选择时候做对比
    goodsNameArr:[],//存放新增商品时候从后端获取商品列表
    fileList:[]//存放新增商品时候从后端获取的图片地址信息
}
class Prizemanger extends Component {
    constructor(props) {
        super(props);
        //定义表格头部信息
        const GridHead = [
            {
                title: '商品类型',
                dataIndex: 'goodsTypeName',
                key: 'goodsTypeName',
            }, {
                title: '商品名称',
                dataIndex: 'goodsName',
                key: 'goodsName',
            }, {
                title: '录入时间',
                dataIndex: 'createTime',
                key: 'createTime',
            }, {
                title: '更新时间',
                dataIndex: 'updateTime',
                key: 'updateTime',
            }, {
                title: '操作',
                key: 'cation',
                render: (text, record) => (
                    <span>
                 <a href="#" onClick={() => this.editGoodsClick(record) }>编辑</a>
            </span>
                )
            }
        ]
        //初始化state值
        this.state = {
            //新增商品弹出框初始化设置
            openBoxTitle: null,//弹出框标题
            addGoodsKey: 1,
            addGoodsBox: addGoodsBox,
            loading: false,
            AddGoodsVisible: false,
            //列表分页条件信息
            pagination: {
                total: 0,
                current: 1,
                defaultPageSize: 10
            },
            goodsName: null,
            goodsTypeName: "全部",
            search: {
                goodsType: '',
                goodsName: ''
            },
            grid: {
                columns: GridHead,
                data: []
            }
        };
    }

    //点击商品列表中的编辑功能
    editGoodsClick = (value) => {
        if (value) {
            //设置弹出框需要显示的内容
            let showRecordInput = false;
            let showGoodsID = false;
            let showGoodsSkuid = false;
            let goodsSourceName = value.goodsSourceName;
            let goodsSource = value.goodsSource;
            let goodsName = value.goodsName;
            let goodsId = value.goodsId;
            let goodsTypeName = value.goodsTypeName;
            let goodsType = value.goodsType;
            let skuList = value.skuList;
            let skuList2 = value.skuList;
            let goodsDesc = value.goodsDesc;
            let integralPrice= value.integralPrice;
            function renderVal(val){
                var selectPropeties= "";
                var regp_name=/(\d*?):(\d*?):(.*?):(.*?)(;|$)/g
                var temp = val
                temp.replace(regp_name,function(v1,v2,v3,v4,v5){
                    selectPropeties+=v5+" ";
                });
                selectPropeties = selectPropeties.split(":").length>1?selectPropeties.split(":")[1]:selectPropeties;
                return selectPropeties;
            };
            //将skulist中的skuval进行字符匹配
            if(skuList2!= null){
                for(let i =0;i< skuList2.length;i++){
                    // skuList2[i].attrVal = renderVal(skuList2[i].attrVal);
                }
            }
            //当skulist后端传为 null 时候，将其等于空数组，乙方在调用数组方法时候报错
            else{
                skuList2 = [];
                skuList = [];
            }

            //按照定义goodstype为2时候则为积分商品
            if (value.goodsType && value.goodsType === "2") {
                showRecordInput = true;
                showGoodsID = false;
                showGoodsSkuid = false;
            }
            //goodstype为1时候为实物商品
            else if (value.goodsType && value.goodsType === "1") {
                showRecordInput = false;
                showGoodsID = true;
                showGoodsSkuid = true;
            }

            this.setState({
                AddGoodsVisible: true,
                openBoxTitle: "编辑商品",
                addGoodsBox: {
                    fileList:[{
                        uid: -1,
                        name: 'xxx.png',
                        status: 'done',
                        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                        thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                    }, {
                        uid: -2,
                        name: 'yyy.png',
                        status: 'done',
                        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                        thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                    }],
                    ableEditType:true,
                    showGoodNameSelect:false,
                    showRecordInput: showRecordInput,
                    showGoodsID: showGoodsID,
                    showGoodsSkuid: showGoodsSkuid,
                    goodsSourceName: goodsSourceName,
                    goodsSource: goodsSource,
                    goodsName: goodsName,
                    goodsId: goodsId,
                    goodsTypeName: goodsTypeName,
                    goodsType: goodsType,

                    integralPrice: integralPrice,
                    goodsDesc: goodsDesc,
                    goodsSkuid: null,
                    skuList:skuList,
                    skuList2:skuList2,
                    goodsNameArr:[]
                }
            })
            console.log(this.state)
        }
    }
    //页面上清除按钮执行重置查询条件操作
    resetSearch = (e) => {
        e.preventDefault();
        this.setState({
            search: {
                goodsType: '',
                goodsName: ''
            },
            goodsTypeName: ''
        })
    }
    //点击搜索或者回车后执行
    searchHandleSubmit = (e) => {
        e.preventDefault();
        this.setState({
            pagination: {
                total: 0,
                current: 1,
                defaultPageSize: 10
            }
        })
        console.log(this.state)
        this.GetListFun()
    }
    //条件筛选商品名称change事件
    searchGoodsName = (value) => {
        let _search = this.state.search;
        _search.goodsName = value.target.value;
        this.setState({
            search: _search
        })
    }
    //条件筛选select changge事件
    searchGoodsTypeChange = (value) => {
        let _search = this.state.search;
        _search.goodsType = value;
        this.setState({
            goodsTypeName: value,
            search: _search
        })
    }
    //点击分页将当前页面赋值给state下的current
    handlePagination = (page, pageSize) => {
        console.log(page, pageSize)
        let _pagination = this.state.pagination;
        _pagination.current = page;
        this.setState({
            pagination: _pagination
        })
        console.log(this.state)
        this.GetListFun()
    }
    //点击新增商品后
    showAddGoodsModal = (name, value) => {
        console.log(name, value)
        this.setState({
            AddGoodsVisible: true,
            openBoxTitle: "新增商品"
        })
    }
    //弹出框点击确定
    addHandleOk = (e) => {
        e.preventDefault();
        let _obj = this.state.addGoodsBox;
        console.log(_obj)
        let _skuList =  [];
        _obj.skuList2.map(function(item2){
            _obj.skuList.map(function(item){
                if(item2.skuId == item.skuId ){
                    _skuList.push(item)
                }
            })
        });
        _obj.skuList=_skuList;
        console.log(_obj)

        this.setState({
            loading: true
        })
        if(_obj.openBoxTitle === '编辑商品'){
            apiInfo({
                path: '/v1/goods/'+_obj.goodsId,
                method: 'put',
                params: _obj
            }).then((data) => {
                if(data == "200"){
                    openNotificationWithIcon('success','成功','商品修改成功')
                    //重新抓取列表数据
                    this.GetListFun()
                    //修改成功后关闭窗口，置空弹出框
                    this.AddHandleCancel()
                }
                else{
                    openNotificationWithIcon('error','失败','商品修改失败，请重试')
                }
                this.setState({
                    loading: false
                })
            })
        }
        else{
            apiInfo({
                path: '/v1/goods/add',
                method: 'post',
                params: _obj
            }).then((data) => {
                if(data == "200"){
                    openNotificationWithIcon('success','成功','商品修改成功')
                    //重新抓取列表数据
                    this.GetListFun()
                    //修改成功后关闭窗口，置空弹出框
                    this.AddHandleCancel()
                }
                else{
                    openNotificationWithIcon('error','失败','商品修改失败，请重试')
                }
                this.setState({
                    loading: false
                })
            })
        }

    }
    //弹出框点击取消
    AddHandleCancel = (e) => {
        if(e){
            e.preventDefault()
        }

        this.setState({
            AddGoodsVisible: false,
            addGoodsBox: {
                showGoodNameSelect:false,
                ableEditType:false,
                showRecordInput: false,
                showGoodsID: false,
                showGoodsSkuid: false,
                goodsSourceName: null,
                goodsName: null,
                integralPrice: null,
                goodsDesc: null,
                goodsSkuid: null,
                goodsId: null,
                skuList:[],
                skuList2:[],
                goodsNameArr:[],
                fileList:[]
            }
        })
        console.log(this.state.addGoodsBox)
    }
    //弹出框 修改商品名称事件
    ChangeGoodsNameSelect = (value) => {
        let _value = value.target.value
        let _obj = this.state.addGoodsBox;
        _obj.goodsName = _value;
        this.setState({
            addGoodsBox: _obj
        })
    }
    //弹出框 修改商品名称事件(select控件)
    ChangeGoodsNameSelect2 = (value) => {
        console.log(value)
        let _obj = this.state.addGoodsBox;
        _obj.goodsId = value;
        let _item = {}
        _obj.goodsNameArr.map(function(item){
            if( String(item.id) == value){
                _item = item;
            }

        })
        _item.itemSkuList.map(function(item){
            item.skuId = item.id;
        })
        _obj.goodsName = _item.name;
        _obj.skuList = _item.itemSkuList;
        _obj.skuList2 = _item.itemSkuList;
        this.setState({
            addGoodsBox : _obj
        })
        console.log(this.state);
    }
    //新增商品select change事件
    AddGoodsSelect = (name, value) => {
        var _value = value;
        if (name === "goodsDesc" || name === "goodsSkuid" || name === "goodsId" || name === "integralPrice") {
            _value = value.target.value
        }
        let _obj = this.state.addGoodsBox
        _obj[name] = _value
        this.setState({
            addGoodsBox: _obj
        })
        console.log(this.state)
    }

    //新增商品选择商品类型 change事件
    AddGoodsSelectType = (value) => {
        let _obj = this.state.addGoodsBox;
        _obj.goodsType = value;
        if (value === "2") {
            _obj.showRecordInput = true;
            _obj.showGoodsID = false;
            _obj.showGoodsSkuid = false;
            _obj.goodsTypeName = '积分';
            _obj.showGoodNameSelect =false;
        }
        else if (value === "1") {
            _obj.showRecordInput = false;
            _obj.showGoodsID = true;
            _obj.showGoodsSkuid = true;
            _obj.goodsTypeName = '实物';
            //向后端请求实物数据
            if(_obj.goodsSource != null){
                apiInfo({
                    path: '/v1/goods/source/'+_obj.goodsSource,
                    method: 'get',
                    params:{pageSize:1000}
                }).then((data) => {
                    if(data.dataList){
                        _obj.goodsNameArr=data.dataList;
                        _obj.showGoodNameSelect = true;
                    }
                    //回调处理后再次设置数据
                    this.setState({
                        addGoodsBox: _obj
                    })
                    console.log(this.state)
                })
            }
        }
        else if (value === "3") {
            _obj.showRecordInput = false;
            _obj.showGoodsID = false;
            _obj.showGoodsSkuid = false;
            _obj.goodsTypeName = '未中奖';
            _obj.showGoodNameSelect =false;
        }
        this.setState({
            addGoodsBox: _obj
        })
    }
    //获取列表页的方法
    GetListFun = () => {
        let _params = this.state.search;
        let _pagination = this.state.pagination;
        let _obj = {};
        //传入参数 商品名称/商品类型/分页的页码
        _obj.goodsName = encodeURI(_params.goodsName);
        _obj.goodsType = _params.goodsType;
        _obj.pageNo = _pagination.current;
        apiInfo({
            path: '/v1/goods/search',
            method: 'get',
            params: _obj
        }).then((data) => {
            if (data.dataList) {
                let grid = this.state.grid;
                grid.data = data.dataList;
                this.setState({
                    grid: grid,
                    pagination: {
                        total: data.total,
                        current: data.pageNo,
                        defaultPageSize: data.pageSize
                    }
                })
            }


        })
    }
    //页面渲染完成后执行代码
    componentDidMount() {
        //页面渲染完成后获取列表代码
        this.GetListFun()
    }
    //选择slulist的tag选择事件
    skulistChange(tag,checked){
        console.log(tag,checked)
        if(!checked){
            let _obj = this.state.addGoodsBox
            let _newarr = []
            for(let i =0 ;i< _obj.skuList2.length;i++){
                if(_obj.skuList2[i].skuId == tag.skuId){
                }
                else{
                    _newarr.push(_obj.skuList2[i])
                }
            }
            _obj.skuList2 = _newarr

            this.setState({
                addGoodsBox: _obj
            })
        }
        //else时候确定为选中tag，将tag放入shulist2中
        else{
            let _obj = this.state.addGoodsBox
            for(let i =0 ;i< _obj.skuList.length;i++){
                if(_obj.skuList[i].skuId == tag.skuId){
                    _obj.skuList2.push(tag)
                }
            }
            this.setState({
                addGoodsBox: _obj
            })
        }
    }
    render() {
        const state = this.state;
        //弹出框表单元素布局使用
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14},
            },
        };
        //新增商品设置
        const AddGoodsProps = {
            action: '//jsonplaceholder.typicode.com/posts/',
            listType: 'picture',
            defaultFileList: [],
        };


        return (
            <div>
                <Form onSubmit={this.searchHandleSubmit}>
                    <FormItem>
                        <Row style={{marginTop: 20, marginBottom: 15}}>
                            <Col span={3} offset={2}>
                                <Input type="text" onChange={this.searchGoodsName.bind(this)}
                                       value={state.search.goodsName} style={{width: 150}}
                                       placeholder="商品名称"/>
                            </Col>
                            <Col span={3}>
                                <Select value={state.goodsTypeName} placeholder="选择商品" style={{width: 150}}
                                        onChange={this.searchGoodsTypeChange}>
                                    <Option value="">全部</Option>
                                    <Option value="1">实物</Option>
                                    <Option value="2">积分</Option>
                                    <Option value="3">未中奖</Option>
                                </Select>
                            </Col>
                            <Col span={2}>
                                <Button type="primary" htmlType="submit">查询</Button>
                            </Col>
                            <Col span={2}>
                                <Button onClick={this.resetSearch}>清除</Button>
                            </Col>
                            <Col span={2} offset={6}>
                                <Button type="primary" icon="plus"
                                        onClick={this.showAddGoodsModal.bind(this, 'addGoods')}>新增</Button>
                            </Col>
                        </Row>
                        <Row style={{marginRight: 40}}>
                            <Col offset={2}>
                                <Table pagination={false} rowKey="goodsId" bordered columns={this.state.grid.columns}
                                       dataSource={this.state.grid.data}/>

                                <Pagination onChange={this.handlePagination}
                                            total={this.state.pagination.total}
                                            defaultCurrent={1}
                                            defaultPageSize={this.state.pagination.defaultPageSize}/>
                            </Col>

                        </Row>
                    </FormItem>
                </Form>
                <Modal
                    key={this.state.addGoodsKey}
                    visible={this.state.AddGoodsVisible}
                    title={this.state.openBoxTitle}
                    onOk={this.addHandleOk}
                    onCancel={this.AddHandleCancel}
                    footer={[
                        <Button key="back" size="large" onClick={this.AddHandleCancel}>返回</Button>,
                        <Button key="submit" type="primary" size="large" loading={this.state.loading}
                                onClick={this.addHandleOk}>
                            确定
                        </Button>
                    ]}
                >
                    <Form>
                        <FormItem
                            {...formItemLayout}
                            label="商品来源"
                        >
                            <Select onChange={this.AddGoodsSelect.bind(this, 'goodsSource')}
                                    value={this.state.addGoodsBox.goodsSource} placeholder="请选择商品来源">
                                <Option value="1">积分商城</Option>
                                <Option value="2">电商</Option>
                            </Select>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="商品类型"
                        >
                            <Select disabled={this.state.addGoodsBox.ableEditType} placeholder="请选择商品类型" value={this.state.addGoodsBox.goodsType}
                                    onChange={this.AddGoodsSelectType}>
                                <Option value="2">积分</Option>
                                <Option value="1">实物</Option>
                                <Option value="3">未中奖</Option>
                            </Select>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="商品名称"
                        >
                            <Select
                                style={{display:this.state.addGoodsBox.showGoodNameSelect ? 'block' :'none'}}
                                showSearch
                                onChange={this.ChangeGoodsNameSelect2}
                                placeholder="请选择商品名称"
                                optionFilterProp="children"
                            >
                                {
                                    this.state.addGoodsBox.goodsNameArr.map(item=>(
                                        <Option key={String(item.id)} value={String(item.id)}>{item.name}</Option>
                                    ))
                                }
                            </Select>
                            <Input style={{display:this.state.addGoodsBox.showGoodNameSelect ? 'none' :'block'}}
                                   onChange={this.ChangeGoodsNameSelect.bind(this)}
                                   value={this.state.addGoodsBox.goodsName} placeholder="输入商品名称"/>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="商品图片"
                        >
                            <Upload
                                action={'//jsonplaceholder.typicode.com/posts/'}
                                listType={'picture'}
                                defaultFileList={this.state.addGoodsBox.fileList}
                            >
                                <Button>
                                    <Icon type="upload"/> 选择图片上传
                                </Button>
                            </Upload>
                            <span>图片大小100x100，小于500KB，PNG、JPG、JPEG格式</span>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="赠送积分"
                            style={{display: this.state.addGoodsBox.showRecordInput ? 'block' : 'none'}}
                        >
                            <Input onChange={this.AddGoodsSelect.bind(this, 'integralPrice')}
                                   value={this.state.addGoodsBox.integralPrice} type='number'
                                   placeholder="输入不大于10000的整数(类型为积分时候输入)"/>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="商品介绍"
                        >
                            <Input onChange={this.AddGoodsSelect.bind(this, 'goodsDesc')}
                                   value={this.state.addGoodsBox.goodsDesc} type="textarea" placeholder="输入商品介绍"/>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="商品ID"
                            style={{display: this.state.addGoodsBox.showGoodsID ? 'block' : 'none'}}
                        >
                            <Input onChange={this.AddGoodsSelect.bind(this, 'goodsId')}
                                   disabled={true}
                                   value={this.state.addGoodsBox.goodsId} placeholder="输入商品ID(类型为实物时候输入)"/>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="商品SKUID"
                            style={{display: this.state.addGoodsBox.showGoodsSkuid ? 'block' : 'none'}}
                        >
                            {/*<Input onChange={this.AddGoodsSelect.bind(this, 'goodsSkuid')}*/}
                                   {/*value={this.state.addGoodsBox.goodsSkuid} placeholder="输入商品SKUID(类型为实物时候输入)"/>*/}
                            <div>
                                    {
                                        this.state.addGoodsBox.skuList.map(tag =>(
                                            <CheckableTag key={tag.skuId}
                                                checked={this.state.addGoodsBox.skuList2.indexOf(tag) > -1}
                                                onChange={checked => this.skulistChange(tag, checked)}
                                                >
                                                {tag.attrVal}
                                            </CheckableTag>
                                        ))
                                    }
                            </div>
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default Prizemanger